package com.philips.util;


import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.Credentials;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.*;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;

import com.alibaba.fastjson.JSON;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;


/**
 * HTTP工具箱
 * 
 * @author Yuanfu 2013-1-9 21:19
 */
public class HttpTool {

	public static enum contentType {
		application_json("application/json"), application_xml("application/xml");
		private String value;

		private contentType(String value) {
			this.value = value;
		}
		public String value() {
			return this.value;
		}

	}

	/**
	 * 模拟Post请求
	 * 
	 * @param url
	 *            路劲
	 * @param params
	 *            参数
	 * @param contentType
	 *            头信息 application/json
	 */
	public static String post(String url, String json, String contentType) {
		try {
			// (1) 创建Httpost实例
			HttpPost httpPost = new HttpPost(url);
			httpPost.setHeader("Content-Type", contentType);
			httpPost.setHeader("Accept", contentType);
			// 设置HTTP POST请求参数
			// httpPost.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));

			httpPost.setEntity(new StringEntity(json, "UTF-8"));
			// (2) 使用HttpClient发送post请求，获得返回结果HttpResponse
			HttpClient http = new DefaultHttpClient();
			HttpResponse response = http.execute(httpPost);
			// (3) 读取返回结果
			HttpEntity entity = response.getEntity();
			InputStream in = entity.getContent();
			return readResponse(in);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;

	}

	public static String get(String url) {
		try {
			HttpGet httpget = new HttpGet(url);
			HttpResponse response = new DefaultHttpClient().execute(httpget);
			HttpEntity entity = response.getEntity();
			InputStream in = entity.getContent();
			return readResponse(in);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;

	}

	public static String readResponse(InputStream in) throws Exception {
		StringBuffer sbf = new StringBuffer();
		BufferedReader reader = new BufferedReader(new InputStreamReader(in));
		String line = null;
		while ((line = reader.readLine()) != null) {
			sbf.append(line);
		}
		return sbf.toString();
	}


	public static void main(String[] args) {
		try {
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	

}